package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.util.AppThreadLocalUtil;
import com.heima.common.constants.ApuserConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.ApUserFollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


/**
 * <p>
 * APP用户关注信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private CacheService cacheService;


    private static final String FOLLOW = "follow:";
    private static final String CANCLE = "cancle";
    @Override
    public ResponseResult follow(UserRelationDto userRelationDto) {
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String redisKey = FOLLOW + userRelationDto.getArticleId();
        if (userRelationDto.getOperation() == ApuserConstants.FOLLOW){
            Object exist = cacheService.hGet(redisKey, user.getId().toString());
            if (exist != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_FOLLOW_EXIST );
            }
            cacheService.hPut(redisKey,user.getId().toString(), JSON.toJSONString(userRelationDto));
        }else {
            cacheService.hDelete(redisKey,user.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
